import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getProfile, getUserDetailById } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 获取token
    updateToken(state, token) {
      state.token = token // 获取token
      setToken(token)
    },
    // 删除token
    deleteToken(state) {
      state.token = null // 删除vuex的token
      removeToken()
    },
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 删除用户信息
    deleteUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, formData) {
      const { data: res } = await login(formData)
      console.log(res.data, 'token')
      context.commit('updateToken', res.data)
    },

    async userInfo(context) {
      const { data: res } = await getProfile()
      console.log(res.data, 'userInfo')
      const { data: info } = await getUserDetailById(res.data.userId)
      console.log(info.data, 'userInfo')
      context.commit('updateUserInfo', { ...info.data, ...res.data })
    },

    logout(context) {
      context.commit('deleteToken')
      context.commit('deleteUserInfo')
    }
  }
}
